from tkinter.font import names

from PySide6.QtWidgets import QWidget,QFileDialog,QMessageBox,QTableWidgetItem,QHeaderView,QMenu,QAbstractItemView
from PySide6.QtCore import Qt
from views.person.other.other import Ui_other
import os,shutil,pandas as pd
from settings.publicvar import engine
from settings.publicFuncation.exceldownloadimport import OperationModel
from sqlalchemy.orm import Session
from views.person.model.person import PersonBaseInfo,PersonOther
from views.person.other.opretionotherView import OperationOther

class OtherView(QWidget,Ui_other):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 参工日期的宽度设置
        self.othertable.setColumnWidth(5,200)
        self.othertable.setColumnWidth(2,150)
        self.othertable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.othertable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.othertable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.othertable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.othertable.customContextMenuRequested.connect(self.generate_menu)
        # 导出模板
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        # 导入数据处理

        self.importbtn.clicked.connect(self.importdataFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.addother.clicked.connect(self.addFun)
        self.loadTableData()

        # 读取所有数据
    def loadTableData(self):
        with Session(engine) as session, session.begin():
            personothers = session.query(PersonOther).all()
            self.setTableStructure(personothers)

    # 表格加载数据
    def setTableStructure(self, data):
        self.othertable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.othertable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.personinfo.name)
            self.othertable.setItem(i, 1, name)
            birthday = QTableWidgetItem(str(item.birthday))
            self.othertable.setItem(i, 2, birthday)
            sex = QTableWidgetItem(item.sex)
            self.othertable.setItem(i, 3, sex)
            nation = QTableWidgetItem(item.nation)
            self.othertable.setItem(i, 4, nation)
            birthplace = QTableWidgetItem(item.birthplace)
            self.othertable.setItem(i, 5, birthplace)
            self.othertable.item(i, 5).setToolTip(item.birthplace)
            domicile = QTableWidgetItem(item.domicile)
            self.othertable.setItem(i, 6, domicile)
            self.othertable.item(i, 6).setToolTip(item.domicile)
            residence = QTableWidgetItem(item.residence)
            self.othertable.setItem(i, 7, residence)
            file_number = QTableWidgetItem(item.file_number)
            self.othertable.setItem(i,8,file_number)
            person_type = QTableWidgetItem(item.person_type)
            self.othertable.setItem(i,9,person_type)
            mark = QTableWidgetItem(item.mark)
            self.othertable.setItem(i,10,mark)

    def generate_menu(self, pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        action = menu.exec(self.othertable.mapToGlobal(pos))
        posrow = self.othertable.currentRow()
        columns = self.othertable.columnCount()
        data = [self.othertable.item(posrow, i).text() for i in range(columns)]
        if action == changeitem:
            changeother = OperationOther('change',data)
            changeother.exec()
        elif action == deletitem:
            deleteother = OperationOther('delete',data)
            deleteother.exec()
        elif action == viewitem:
            viewother = OperationOther('view',data)
            viewother.exec()
        self.loadTableData()

    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('人员扩展信息模板.xlsx')

    def importdataFun(self):
        other_names = ['idx','name','IDcard','birthday','sex','nation','birthplace','domicile','residence','file_number','person_type','mark']
        parse_dates = ['birthday', ]
        dtypes = {'IDcard': str, 'iphone': str}
        data = OperationModel().importdataFun(other_names,dtypes,parse_dates=parse_dates)
        data['birthday'] = data['birthday'].replace({pd.NaT: None})
        with Session(engine) as session,session.begin():
            exist_personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()
            tem = []
            for item in exist_personbase:
                personothers = item.personothers
                if not personothers:
                    tem.append((item.IDcard,item.id))
            exist_personbase = tem
            exist_IDcard = [item[0] for item in exist_personbase]
            exist_personbase = pd.DataFrame(exist_personbase).rename(columns={1:'name_id',0:'IDcard'})
            save_personother = data[data['IDcard'].isin(exist_IDcard)]
            save_personother = pd.merge(exist_personbase, save_personother, on='IDcard').drop(columns=['name', 'IDcard']).to_dict('records')
            personothers = [PersonOther(**item) for item in save_personother]
            session.add_all(personothers)
            QMessageBox.information(None, '提示', '你导入成功%s条，失败%s条，明细如下！' % (len(personothers), len(data) - len(personothers)))
        self.loadTableData()

    # 搜索框数据处理
    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                others = []
                if sereachData:
                    for personbase in sereachData:
                        for other in personbase.personothers:
                            others.append(other)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')
                self.setTableStructure(others)

    def addFun(self):
        addOther = OperationOther('add',False)
        addOther.exec()
        self.loadTableData()